package cn.miao.photoprinter.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import cn.miao.photoprinter.R;
import cn.miao.photoprinter.adapter.Cart2OrderAdapter;
import cn.miao.photoprinter.entity.ShoppingCart;
import cn.miao.photoprinter.util.ImageHelper;
import cn.miao.photoprinter.util.ZipUtil;
import cn.miao.photoprinter.view.LoadingDialog;

public class Cart2OrderActivity extends Activity {

	private static final int LOADOK = 10001;
	private static final int INFOUPLOAD = 10002;
	private static Handler handler;
	ListView shoppingCart;
	Cart2OrderAdapter adapter;
	Button btnPay;
	LoadingDialog dialog;
	TextView orderId;
	EditText address, consignee, phone;
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cart2order);
		dialog = new LoadingDialog(this, "数据上传中...");
		dialog.setCancelable(true);
		
		List<ShoppingCart> list = (List<ShoppingCart>) getIntent().getExtras()
				.getSerializable("data");
		handler = new MyHandler(this);

		shoppingCart = (ListView) findViewById(R.id.shoppingcart);
		adapter = new Cart2OrderAdapter(this);
		adapter.addAll(list);
		shoppingCart.setAdapter(adapter);
		shoppingCart.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				Cart2OrderAdapter adapter = (Cart2OrderAdapter) parent
						.getAdapter();
				ShoppingCart cart = adapter.getItem(position);
				System.out.println("ItemLongClick:" + cart.getShop());
				return false;
			}
		});
		shoppingCart.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Cart2OrderAdapter adapter = (Cart2OrderAdapter) parent
						.getAdapter();
				ShoppingCart cart = adapter.getItem(position);
				System.out.println("onitemclick:" + cart.getShop() + "."
						+ cart.isChecked());
			}
		});

		btnPay = (Button) findViewById(R.id.bt_pay);
		btnPay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final String fileServer = "http://www.htwater.net:8080/photoprint/uploadservlet?m=takeprint";
				// CameraHelper.uploadFile(fileServer,
				// camRoot + currentImage, params);
				final ShoppingCart cart = adapter.getAllCart().get(0);
				final File tmp = Environment
						.getExternalStoragePublicDirectory("photoprint/tmp");
				if (!tmp.exists()) {
					tmp.mkdir();
				}
				System.out.println(cart.toMap());
				dialog.show();
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss",
								Locale.CHINA);
						// TODO set user id as a part of filename
						String fileName = "userid_"+format.format(new Date()) + ".zip";
						String zipFileString = tmp.getPath() + "/" + fileName;
						String[] files = cart.getPhotos().split(",");
						try {
							ZipUtil.writeByApacheZipOutputStream(files, zipFileString, "Compressed By PhotoPrint");
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
						Map<String, String> uploadMap = new HashMap<String, String>();
						uploadMap.put("orderid", orderId.getText().toString());
						uploadMap.put("address", address.getText().toString());
						uploadMap.put("consignee", consignee.getText().toString());
						uploadMap.put("phone", phone.getText().toString());
						uploadMap.putAll(cart.toMap());
						// TODO 上传成功就删除，否则保存为未处理订单
						ImageHelper.apacheUploadFile(fileServer, zipFileString,
								uploadMap);
						handler.sendEmptyMessage(INFOUPLOAD);
					}
				}).start();

			}
		});
		orderId = (TextView) findViewById(R.id.orderid);
		orderId.setText(getOderid());
		address = (EditText) findViewById(R.id.address);
		consignee = (EditText) findViewById(R.id.consignee);
		phone = (EditText) findViewById(R.id.phone);
	}
	
	private String getOderid() {
		DateFormat format = new SimpleDateFormat("yyMMddHHmmss", Locale.CHINA);
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		int random = r.nextInt(1000000);
		System.out.println(random);
		key += random;
		key = key.substring(0, 15);
		return key;
	}

	@Override
	public void onBackPressed() {
		setResult(Activity.RESULT_OK, new Intent());
		finish();
	}

	static class MyHandler extends Handler {

		WeakReference<Cart2OrderActivity> context;

		public MyHandler(Cart2OrderActivity context) {
			this.context = new WeakReference<Cart2OrderActivity>(context);
		}

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			Cart2OrderActivity activity = context.get();
			switch (msg.what) {
			case LOADOK:
				List<ShoppingCart> records = (List<ShoppingCart>) msg.obj;
				activity.adapter = new Cart2OrderAdapter(activity, records);
				activity.shoppingCart.setAdapter(activity.adapter);
				break;
			case INFOUPLOAD:
				activity.dialog.dismiss();
				break;
			}
			super.handleMessage(msg);
		}
	}
}
